import React, { PureComponent } from 'react';
import { List, Icon, Tag, Button } from 'antd';
import { connect } from 'dva';
import Link from 'umi/link';
import ArticleListContent from '@/components/ArticleListContent';
import styles from './Articles.less';

const pageSize = 15;
let pageNo = 1;

@connect(({ post, loading }) => ({
  post,
  loading: loading.models.post,
  listLoading: loading.effects['post/fetchPostByUser'],
}))
class Center extends PureComponent {

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'post/fetchPostByUser',
      payload: {
        userId: this.props.match.params.id,
        page: 1,
        size: pageSize,
      },
    });
  }

  fetchMore = () => {
    const { dispatch } = this.props;
    pageNo += 1;
    dispatch({
      type: 'post/appendFetchPostByUser',
      payload: {
        userId: this.props.match.params.id,
        page: pageNo,
        size: pageSize,
      },
    });
  };

  render() {
    const {
      post: { postByUser },
      loading,
      listLoading,
    } = this.props;
    const IconText = ({ type, text }) => (
      <span>
        <Icon type={type} style={{ marginRight: 8 }} />
        {text}
      </span>
    );

    const loadMore =
      postByUser.length > 0 ? (
        <div style={{ textAlign: 'center', marginTop: 16 }}>
          <Button onClick={this.fetchMore} style={{ paddingLeft: 48, paddingRight: 48 }}>
            {loading ? (
              <span>
                <Icon type="loading" /> 加载中...
              </span>
            ) : (
              '加载更多'
            )}
          </Button>
        </div>
      ) : null;

    return (
      <List
        size="large"
        loading={listLoading}
        className={styles.articleList}
        rowKey="id"
        itemLayout="vertical"
        dataSource={postByUser}
        loadMore={loadMore}
        renderItem={item => (
          <List.Item
            key={item.id}
            actions={[
              <IconText type="eye-o" text={item.viewsCount} />,
              <IconText type="star-o" text={item.collectionCount} />,
              <IconText type="like-o" text={item.subscribersCount} />,
              <IconText type="message" text={item.commentsCount} />,
            ]}
          >
            <List.Item.Meta
              title={
                <Link to={`/post/detail/${item.id}`}>{item.title}</Link>
              }
              description={
                <span>
                  {item.tags.map(it => (
                    <Tag key={it.id}>{it.title}</Tag>
                  ))}
                </span>
              }
            />
            <ArticleListContent data={item} />
          </List.Item>
        )}
      />
      
    );
  }
}

export default Center;
